import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Table,
  Upload
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './Room.less';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['未入住', '清洁中', '已入住', '暂不出租'];

@Form.create()
class CreateForm extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      formVals: {
        room_number: '',
        price: '',
        title: '',
        residents: '',
        headimgurl:[],
        imgs:[],
      },
      
      currentStep: 0,
    };

    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }

  handleNext = currentStep => {
    const { form, handleUpdate } = this.props;
    const { formVals: oldValue } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formVals = { ...oldValue, ...fieldsValue };
      this.setState(
        {
          formVals,
        },
        () => {
          if (currentStep < 2) {
            this.forward();
          } else {
            handleUpdate(formVals);
          }
        }
      );
    });
  };

  backward = () => {
    const { currentStep } = this.state;
    this.setState({
      currentStep: currentStep - 1,
    });
  };

  forward = () => {
    const { currentStep } = this.state;
    this.setState({
      currentStep: currentStep + 1,
    });
  };

  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }

  handleHeaaImgUrlChange = ({ fileList }) => {
    for(let i=0; i<fileList.length; i++){
      if(fileList[i].response && fileList[i].response.status === "SUCCESS" && fileList[i].status === "done"){
        fileList[i]['url'] = fileList[i].response.data
      }
    }
    this.setState({ 
      ...this.state,
      formVals:{
        ...this.state.formVals,
        headimgurl:fileList
      }
    })
  }

  handleImgsChange = ({ fileList }) => {
    for(let i=0; i<fileList.length; i++){
      if(fileList[i].response && fileList[i].response.status === "SUCCESS" && fileList[i].status === "done"){
        fileList[i]['url'] = fileList[i].response.data
      }
    }
    this.setState({ 
      ...this.state,
      formVals:{
        ...this.state.formVals,
        imgs:fileList
      }
    })
  }

  renderContent = (currentStep, formVals) => {
    const { form } = this.props;
    if (currentStep === 1) {
      return [
        <div className={styles.img}>
          <Upload 
            action="/api/api/tool/upload/img"
            listType="picture-card"
            name="img"
            fileList={formVals.headimgurl}
            onPreview={this.handlePreview}
            onChange={this.handleHeaaImgUrlChange}
          >
            {
              formVals.headimgurl.length > 0
              ?null:
              <div>
                <Icon type="plus" />
                <div className="ant-upload-text">Upload</div>
              </div>
            }
          </Upload>
        </div>
      ];
    }
    if (currentStep === 2) {
      return [
        <div className={styles.img}>
          <Upload 
            action="/api/api/tool/upload/img"
            listType="picture-card"
            name="img"
            fileList={formVals.imgs}
            onPreview={this.handlePreview}
            onChange={this.handleImgsChange}
          >
            {
              formVals.imgs.length > 20
              ?null:
              <div>
                <Icon type="plus" />
                <div className="ant-upload-text">Upload</div>
              </div>
            }
          </Upload>
        </div>
      ];
    }
    return [
      <FormItem key="title" {...this.formLayout} label="标题">
        {form.getFieldDecorator('title', {
          rules: [{ required: true, message: '请输入推广标题！' }],
          initialValue: formVals.title,
        })(<Input placeholder="请输入推广标题" />)}
      </FormItem>,
      <FormItem key="room_number" {...this.formLayout} label="房间号">
        {form.getFieldDecorator('room_number', {
          rules: [{ required: true, message: '请输入房间号！' }],
          initialValue: formVals.room_number,
        })(<Input placeholder="请输入房间号" />)}
      </FormItem>,
      <FormItem key="price" {...this.formLayout} label="单价">
        {form.getFieldDecorator('price', {
          rules: [{ required: true, message: '请输入单价！' }],
          initialValue: formVals.price,
        })(<Input placeholder="请输入单价" />)}
      </FormItem>,
      <FormItem key="residents" {...this.formLayout} label="可入住人数">
        {form.getFieldDecorator('residents', {
          rules: [{ required: true, message: '可入住人数！' }],
          initialValue: formVals.residents,
        })(<Input placeholder="可入住人数" />)}
      </FormItem>,
    ];
  };

  renderFooter = currentStep => {
    const { handleUpdateModalVisible } = this.props;
    if (currentStep === 1) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
          取消
        </Button>,
        <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
          下一步
        </Button>,
      ];
    }
    if (currentStep === 2) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={() => this.handleNext(currentStep)}>
          完成
        </Button>,
      ];
    }
    return [
      <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
        取消
      </Button>,
      <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
        下一步
      </Button>,
    ];
  };

  render() {
    const { modalVisible, handleUpdateModalVisible } = this.props;
    const { currentStep, formVals } = this.state;

    return (
      <Modal
        width={640}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title="添加房间"
        visible={modalVisible}
        footer={this.renderFooter(currentStep)}
        onCancel={() => handleUpdateModalVisible()}
      >
        <Steps style={{ marginBottom: 28 }} size="small" current={currentStep}>
          <Step title="基本信息" />
          <Step title="列表展示图" />
          <Step title="房间环境图" />
        </Steps>
        {this.renderContent(currentStep, formVals)}
      </Modal>
    );
  }
}

@Form.create()
class UpdateForm extends PureComponent {
  constructor(props) {
    super(props);

    let imgs = [];
    for(let i = 0; i<props.values.imgs.length; i++){
      imgs.push({
          uid: i,
          status: 'done',
          url:props.values.imgs[i]
      });
    }

    this.state = {
      formVals: {
        room_number: props.values.room_number,
        price: props.values.price,
        title: props.values.title,
        residents: props.values.residents,
        headimgurl:[{
          uid: '-1',
          name: 'xxx.png',
          status: 'done',
          url:props.values.headimgurl
        }],
        imgs:imgs,
      },
      
      currentStep: 0,
    };

    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }

  handleNext = currentStep => {
    const { form, handleUpdate } = this.props;
    const { formVals: oldValue } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formVals = { ...oldValue, ...fieldsValue };
      this.setState(
        {
          formVals,
        },
        () => {
          if (currentStep < 2) {
            this.forward();
          } else {
            formVals.id = this.props.values.id;
            handleUpdate(formVals);
          }
        }
      );
    });
  };

  backward = () => {
    const { currentStep } = this.state;
    this.setState({
      currentStep: currentStep - 1,
    });
  };

  forward = () => {
    const { currentStep } = this.state;
    this.setState({
      currentStep: currentStep + 1,
    });
  };

  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }

  handleHeaaImgUrlChange = ({ fileList }) => {
    for(let i=0; i<fileList.length; i++){
      if(fileList[i].response && fileList[i].response.status === "SUCCESS" && fileList[i].status === "done"){
        fileList[i]['url'] = fileList[i].response.data
      }
    }
    this.setState({ 
      ...this.state,
      formVals:{
        ...this.state.formVals,
        headimgurl:fileList
      }
    })
  }

  handleImgsChange = ({ fileList }) => {
    for(let i=0; i<fileList.length; i++){
      if(fileList[i].response && fileList[i].response.status === "SUCCESS" && fileList[i].status === "done"){
        fileList[i]['url'] = fileList[i].response.data
      }
    }
    this.setState({ 
      ...this.state,
      formVals:{
        ...this.state.formVals,
        imgs:fileList
      }
    })
  }

  renderContent = (currentStep, formVals) => {
    const { form } = this.props;
    if (currentStep === 1) {
      return [
        <div className={styles.img}>
          <Upload 
            action="/api/api/tool/upload/img"
            listType="picture-card"
            name="img"
            fileList={formVals.headimgurl}
            onPreview={this.handlePreview}
            onChange={this.handleHeaaImgUrlChange}
          >
            {
              formVals.headimgurl.length > 0
              ?null:
              <div>
                <Icon type="plus" />
                <div className="ant-upload-text">Upload</div>
              </div>
            }
          </Upload>
        </div>
      ];
    }
    if (currentStep === 2) {
      return [
        <div className={styles.img}>
          <Upload 
            action="/api/api/tool/upload/img"
            listType="picture-card"
            name="img"
            fileList={formVals.imgs}
            onPreview={this.handlePreview}
            onChange={this.handleImgsChange}
          >
            {
              formVals.imgs.length > 20
              ?null:
              <div>
                <Icon type="plus" />
                <div className="ant-upload-text">Upload</div>
              </div>
            }
          </Upload>
        </div>
      ];
    }
    return [
      <FormItem key="title" {...this.formLayout} label="标题">
        {form.getFieldDecorator('title', {
          rules: [{ required: true, message: '请输入推广标题！' }],
          initialValue: formVals.title,
        })(<Input placeholder="请输入推广标题" />)}
      </FormItem>,
      <FormItem key="room_number" {...this.formLayout} label="房间号">
        {form.getFieldDecorator('room_number', {
          rules: [{ required: true, message: '请输入房间号！' }],
          initialValue: formVals.room_number,
        })(<Input placeholder="请输入房间号" />)}
      </FormItem>,
      <FormItem key="price" {...this.formLayout} label="单价">
        {form.getFieldDecorator('price', {
          rules: [{ required: true, message: '请输入单价！' }],
          initialValue: formVals.price,
        })(<Input placeholder="请输入单价" />)}
      </FormItem>,
      <FormItem key="residents" {...this.formLayout} label="可入住人数">
        {form.getFieldDecorator('residents', {
          rules: [{ required: true, message: '可入住人数！' }],
          initialValue: formVals.residents,
        })(<Input placeholder="可入住人数" />)}
      </FormItem>,
    ];
  };

  renderFooter = currentStep => {
    const { handleUpdateModalVisible } = this.props;
    if (currentStep === 1) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
          取消
        </Button>,
        <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
          下一步
        </Button>,
      ];
    }
    if (currentStep === 2) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={() => this.handleNext(currentStep)}>
          完成
        </Button>,
      ];
    }
    return [
      <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
        取消
      </Button>,
      <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
        下一步
      </Button>,
    ];
  };

  render() {
    const { updateModalVisible, handleUpdateModalVisible } = this.props;
    const { currentStep, formVals } = this.state;

    return (
      <Modal
        width={640}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title="修改房间"
        visible={updateModalVisible}
        footer={this.renderFooter(currentStep)}
        onCancel={() => handleUpdateModalVisible()}
      >
        <Steps style={{ marginBottom: 28 }} size="small" current={currentStep}>
          <Step title="基本信息" />
          <Step title="列表展示图" />
          <Step title="房间环境图" />
        </Steps>
        {this.renderContent(currentStep, formVals)}
      </Modal>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ loading, hotel }) => ({
  hotel,
  loading: loading.models.hotel,
}))
@Form.create()
class Room extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
  };

  columns = [
    {
      title: '房间号',
      dataIndex: 'room_number',
      key:'room_number'
    },
    {
      title: '价格',
      dataIndex: 'price',
      key:'price'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key:'status',
      filters: [
        {
          text: status[0],
          value: 0,
        },
        {
          text: status[1],
          value: 1,
        },
        {
          text: status[2],
          value: 2,
        },
        {
          text: status[3],
          value: 3,
        },
      ],
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleUpdateModalVisible(true, record)}>修改</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { hotel, dispatch } = this.props;
    dispatch({
      type: 'hotel/fetchHotelRoom',
      payload: hotel.id
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'hotel/fetchHotelRoom',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'hotel/fetchHotelRoom',
      payload: {},
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'rule/remove',
          payload: {
            key: selectedRows.map(row => row.key),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'hotel/fetchHotelRoom',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      stepFormValues: record || {},
    });
  };
  handleUpdate = fields => {
    let formData = {};
    formData.price = fields.price;
    formData.residents = fields.residents;
    formData.room_number = fields.room_number;
    formData.title = fields.title;
    formData.id = fields.id;
    formData.headimgurl = fields.headimgurl[0].url;
    formData.imgs = [];
    for(let i=0; i<fields.imgs.length; i++){
      formData.imgs.push(fields.imgs[i].url)
    }
    const { dispatch, hotel } = this.props;
    if(formData.id){
      dispatch({
        type: 'hotel/fetchUpdateRoom',
        payload: formData,
      });
      this.handleUpdateModalVisible();
    }else{
      formData.hotel_id = hotel.id;
      dispatch({
        type: 'hotel/fetchAddRoom',
        payload: formData,
      });
      this.handleModalVisible();
    }
    
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="房间号">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="房间状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">未入住</Option>
                  <Option value="1">清洁中</Option>
                  <Option value="2">已入住</Option>
                  <Option value="3">暂不出租</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const {
      hotel,
      loading,
    } = this.props;

    const { selectedRows, modalVisible, updateModalVisible, stepFormValues } = this.state;
    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    return (
      <PageHeaderWrapper title={`${hotel.name}房间管理`}>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新建
              </Button>
            </div>
            <Table
              loading={loading}
              dataSource={hotel.list}
              pagination={hotel.pagination}
              columns={this.columns}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...updateMethods} modalVisible={modalVisible} />
        {stepFormValues && Object.keys(stepFormValues).length ? (
          <UpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={stepFormValues}
          />
        ) : null}
      </PageHeaderWrapper>
    );
  }
}

export default Room;
